import styled from "@emotion/styled"
import { AssetKeySvg } from "custom/asset_key"
import { useAtomValue, getDefaultStore } from "jotai"
import { atomFamily, atomWithDefault } from "jotai/utils"
import { createLogger } from "@/utils/logger"
import { resolveAssetSvg } from "@/utils/common"
import { Suspense } from "react"

const jotai = getDefaultStore()
const logger = createLogger("components/base/Svg")

const SvgStyled = styled.svg``

type SvgProps = ExtractStyledProps<typeof SvgStyled>

type Props = Omit<SvgProps, "src"> & {
    src: AssetKeySvg
}

const svgAtomFamilyAsync = atomFamily((src: AssetKeySvg) => {
    return atomWithDefault(() => {
        const module = resolveAssetSvg(src)
        // @ts-ignore
        return module?.default || module
    })
})

export default function Svg(props: Props) {
    const { src: assets_src, ...rest } = props
    const SvgComponent = useAtomValue(
        svgAtomFamilyAsync(assets_src),
    ) as React.ComponentType<SvgProps>

    return (
        <Suspense>
            <SvgComponent {...rest} />
        </Suspense>
    )
}
export function SvgComponent(src: AssetKeySvg) {
    const Output = jotai.get(svgAtomFamilyAsync(src)) as unknown as React.ComponentType<SvgProps>
    return function SvgComponentWrapper(props: SvgProps) {
        return (
            <Suspense>
                <Output {...props} />
            </Suspense>
        )
    }
}
